/*
 * @lc app=leetcode.cn id=543 lang=cpp
 *
 * [543] 二叉树的直径
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    int ans = 0;

    int longest(TreeNode* root, int height)
    {
        if(root == nullptr) return height - 1;
        int left_height = longest(root->left, height + 1);
        int right_height = longest(root->right, height + 1);
        ans = std::max(ans, left_height + right_height - 2 * height);
        return std::max(left_height, right_height);
    }

public:
    int diameterOfBinaryTree(TreeNode* root) {
        longest(root, 1);
        return ans;
    }
};
// @lc code=end

